<?php

namespace App\Http\Controllers\Home;

use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\SMS\SendTemplateSMS;
use App\SMS\M3Result;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    //手机注册页面
    public function index(){
        return view("home.register");
    }
    //发送验证码
    public function sendcode(Request $request){

        //获取要发送的手机号
        $phone = $request->input('phone');

        //生成模板的参数，验证码和时间
        $code = rand(1000,9999);
        $arr = [$code,5];

        //调用 容联云通信的接口
        $templateSMS =  new SendTemplateSMS();
        $M3result = new M3Result();
        $M3result = $templateSMS->sendTemplateSMS($phone,$arr,'1');

        //将验证码存入session
        session()->put('phone',$code);

        //给客户端返回响应结果
        return $M3result->toJson();

    }

    //执行注册
    public function dophoneregister(Request $request){

        //判断验证码是否正确
        $yzpass = $request->input('yzpass');
        if($yzpass!=session()->get('phone')){
            $data = [
                'status' => 2,
                'message'=> '验证码错误！'
            ];
            return $data;
        }

        //验证是否有此用户
        $user = User::where('user_name','=',$request->input('user_name'))->first();
        if($user){
            $data = [
                'status' => 3,
                'message'=> '用户已存在！'
            ];
            return $data;
        }

        $input = $request->except('yzpass','_token');
        $input['user_pass'] = Crypt::encrypt($input['user_pass']);
        //return $input;
        $user = User::create($input);

        if($user){
            $data = [
                'status' => 0,
                'message'=> '注册成功！'
            ];
        }else{
            $data = [
                'status' => 1,
                'message'=> '注册失败！'
            ];
        }
        //json_decode();
        return $data;

    }

    //邮箱注册页面
    public function emailregister(){
        return view("home.emailregister");
    }

    //发送邮箱验证码
    public function doregister(Request $request){
        $input = $request->except("_token");

        $input['user_pass'] = Crypt::encrypt($input['user_pass']);
        $input['token'] = md5($input['email'].$input['user_pass'].'123');
        $input['expire'] = time()+3600*24;
        //return $input;
        $user = User::create($input);
        if($user){
            Mail::send('email.active',['user'=>$user],function ($m) use ($user){
                $m->to($user->email,$user->name)->subject('激活邮箱');
            });

            return redirect('login')->with('active','请先登录激活邮箱账号');
        }else{
            return redirect('emailregister');
        }
    }

}
